const userGoodsDao = require('../../dao/modules/userGoodsDao.js')

module.exports = async (obj, originalParam) => {
	let user_order_success = true;
	let {
		data = {}, verifyResult
	} = obj;
	let {
		db,
		_
	} = originalParam;
	let {
		out_trade_no,
		total_fee
	} = data;

	//设置订单支付成功
	await db.collection('uni-id-base-order').doc(out_trade_no)
		.update({
			status: 2,
			transaction_id: data.payNo,
			paid_time: new Date().getTime(),
			update_time: new Date().getTime()
		});
	let order = await db.collection('uni-id-base-order').where({
		_id: out_trade_no
	}).get()
	let user = await db.collection('uni-id-users').where({
		_id: order.data[0].user_id
	}).get()

	// let user = await db.collection('uni-id-user').doc(curOrder.data.user_id)

	//----发货----
	let goods = await db.collection('order_goods').where({
		oid: out_trade_no
	}).get()
	let course = await db.collection('course').where({
		_id: goods.data[0].goods_id
	}).get()

	let ids = []
	let userGoods = goods.data.map(v => {
		//后期可以再加入课程有效期 分销逻辑等
		let item = {
			user_id: v.user_id,
			goods_id: v.goods_id,
			goods_type: v.type,
			oid: v.oid
		}
		ids.push(v.goods_id)
		return item
	})

	//课程订阅人数+1
	let addRes = await db.collection('course').where({
		_id: _.in(ids)
	}).update({
		"user_count": _.inc(1)
	})

	let res = await userGoodsDao.addAllUserGoods(userGoods)
	let accessToken
	let callFunctionRes = await uniCloud.callFunction({
		name: "router",
		data: {
			$url: 'client/pub/index',
		}
	});
	if (callFunctionRes.result.code === 0) {
		accessToken = callFunctionRes.result.data.token; // 表示你后端执行成功了
		await uniCloud.callFunction({
			name: "router",
			data: {
				$url: 'client/pub/template',
				data: {
					openId: user.data[0].wx_openid.h5,
					accessToken: accessToken,
					template_id: 'ZR1hWTAUDqQyUYp5l_HrB8jmVjKySKgpGj9B8Haok_8',
					data: {
						thing2: {
							value: course.data[0].title
						},
						thing7: {
							value: user.data[0].nickname
						},
						character_string6: {
							value: order.data[0].order_no
						},
						amount5: {
							value: order.data[0].total_fee / 100
						},
						time3: {
							value: order.data[0]._add_time_str
						},
					}
				},
			}
		});
	}
	return user_order_success;
};